<template>
    <div class="order-checkout">
        <!-- 步骤条 -->
        <el-steps :active="activeStep" finish-status="success">
            <el-step title="确认订单"></el-step>
            <el-step title="填写核对订单信息"></el-step>
            <el-step title="完成"></el-step>
        </el-steps>

        <!-- 步骤内容 -->
        <div class="step-content">
            <!-- 步骤 1: 确认订单 -->
            <div v-if="activeStep === 0">
                <h2>确认订单</h2>
                <!-- 收货地址 -->
                <div class="address-section">
                    <!-- 搜索框 -->
                    <div class="address-header">
                        <h4>选择自提点</h4>
                        <div class="address-search">
                            <el-input
                                v-model="formInline.SearchMerchantAddress"
                                placeholder="输入地址关键词搜索"
                                clearable
                                @clear="handleSearchClear"
                                @keyup.enter.native="onSubmit">
                                <el-button
                                    slot="append"
                                    icon="el-icon-search"
                                    @click="onSubmit">
                                </el-button>
                            </el-input>
                        </div>
                    </div>
                    <!-- 选择自提点 -->
                    <div v-loading="addressLoading" class="address-container">
                        <el-radio-group v-model="selectedAddress" class="address-list">
                            <el-radio
                                v-for="address in addressesList"
                                :key="address.merchantId"
                                :label="address.merchantId"
                                class="address-item">
                                <div class="address-card">
                                    <div class="merchant-logo">
                                        <el-image
                                            :src="address.logo"
                                            fit="cover"
                                            class="merchant-image">
                                            <div slot="error" class="image-error">
                                                <i class="el-icon-picture-outline"></i>
                                            </div>
                                        </el-image>
                                    </div>
                                    <div class="merchant-info">
                                        <div class="merchant-name">
                                            <span>{{address.name}}</span>
                                            <el-tag v-if="address.isDefault" size="mini" type="success">默认</el-tag>
                                        </div>
                                        <div class="merchant-address">
                                            <i class="el-icon-location"></i>
                                            <span>{{address.address}}{{address.addressDetail}}</span>
                                        </div>
                                        <div class="merchant-contact">
                                            <i class="el-icon-phone"></i>
                                            <span>{{address.phone || '暂无联系电话'}}</span>
                                        </div>
                                    </div>
                                </div>
                            </el-radio>
                        </el-radio-group>

                        <div v-if="addressesList.length === 0" class="no-address">
                            <el-empty description="未找到匹配的自提点">
                                <el-button type="primary" @click="resetSearch">重置搜索条件</el-button>
                            </el-empty>
                        </div>

                        <div class="pagination-container" v-if="total > 0">
                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="current"
                                :page-sizes="currentList"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
                <!-- 订单信息 -->
                <div class="order-info">
                    <h4>订单信息</h4>
                    <el-table :data="CartsTableData" style="width: 100%">
                        <el-table-column prop="cartId" label="购物车Id"></el-table-column>
                        <el-table-column prop="product.name" label="商品名称"></el-table-column>
                        <el-table-column prop="imageUrl" label="商品图片" width="120">
                            <template #default="scope">
                                <img :src="scope.row.image[0].imageUrl" alt="imageUrl" style="width: 50px; height: 50px">
                            </template>
                        </el-table-column>
                        <el-table-column prop="product.salePrice" label="单价" width="120"></el-table-column>
                        <el-table-column prop="sum" label="数量" width="120"></el-table-column>
                        <el-table-column prop="subtotal" label="总价" width="120">
                            <template #default="scope">
                                {{ (scope.row.product.salePrice * scope.row.sum).toFixed(2) }}
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="total-price">
                        <strong>总价：{{ totalPrice.toFixed(2) }} 元</strong>
                    </div>
                </div>

                <!-- 操作按钮 -->
                <el-button type="primary" @click="nextStep(0)" :disabled="!selectedAddress">下一步</el-button>
            </div>

            <!-- 步骤 2: 支付 -->
            <div v-if="activeStep === 1" class="step-two">
                <h3>支付订单</h3>
                <!-- 订单信息卡片 -->
                <div class="order-summary-card">
                    <div class="order-summary-header">
                        <i class="el-icon-shopping-cart-2"></i>
                        <span>订单信息</span>
                    </div>
                    <div class="order-summary-content">
                        <div class="order-info-row">
                            <span>订单编号：</span>
                            <span>{{this.orderId}}</span>
                        </div>
                        <div class="order-info-row">
                            <span>商品金额：</span>
                            <span>¥{{ totalPrice.toFixed(2) }}</span>
                        </div>
                        <div class="order-info-row">
                            <span>运费：</span>
                            <span>¥0.00</span>
                        </div>
                        <div class="order-info-row total">
                            <span>应付总额：</span>
                            <span class="total-amount">¥{{ totalPrice.toFixed(2) }}</span>
                        </div>
                    </div>
                </div>
                <!-- 支付方式 -->
                <div class="payment-section">
                    <h4>选择支付方式</h4>
                    <el-radio-group v-model="selectedPayment" class="payment-methods">
                        <!-- 支付宝支付 -->
                        <el-radio label="alipay" class="payment-method">
                            <div class="payment-content">
                                <div class="payment-icon">
                                    <img :src="require('@/assets/zhifu/zfb.png')" alt="支付宝" class="payment-logo">
                                </div>
                                <div class="payment-info">
                                    <div class="payment-name">支付宝支付</div>
                                    <div class="payment-desc">安全快捷的支付方式</div>
                                </div>
                                <div class="payment-tag">
                                    <el-tag size="mini" type="success">推荐</el-tag>
                                </div>
                            </div>
                        </el-radio>

                        <!-- 微信支付 -->
                        <el-radio label="wechat" class="payment-method">
                            <div class="payment-content">
                                <div class="payment-icon">
                                    <img :src="require('@/assets/zhifu/wx.png')" alt="微信支付" class="payment-logo">
                                </div>
                                <div class="payment-info">
                                    <div class="payment-name">微信支付</div>
                                    <div class="payment-desc">微信用户专享</div>
                                </div>
                            </div>
                        </el-radio>

                        <!-- 银行卡支付 -->
                        <el-radio label="bank" class="payment-method">
                            <div class="payment-content">
                                <div class="payment-icon">
                                    <img src="https://img.icons8.com/color/48/000000/bank-card-back-side.png" alt="银行卡" class="payment-logo">
                                </div>
                                <div class="payment-info">
                                    <div class="payment-name">银行卡支付</div>
                                    <div class="payment-desc">支持储蓄卡/信用卡</div>
                                </div>
                            </div>
                        </el-radio>
                    </el-radio-group>
                </div>


                <!-- 支付协议 -->
                <div class="payment-agreement">
                    <el-checkbox v-model="agreeAgreement">
                        我已阅读并同意
                        <el-link type="primary" :underline="false">《支付协议》</el-link>
                        和
                        <el-link type="primary" :underline="false">《退款协议》</el-link>
                    </el-checkbox>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <el-button @click="prevStep">返回修改</el-button>
                    <el-button
                        type="primary"
                        @click="handlePayment"
                        :loading="paying"
                        :disabled="!selectedPayment || !agreeAgreement">
                        立即支付
                    </el-button>
                </div>
            </div>

            <!-- 步骤 3: 完成 -->
            <div v-if="activeStep === 2" class="step-three">
                <el-result
                    icon="success"
                    title="支付成功">
                    <template slot="extra">
                        <div class="action-buttons">
                            <el-button @click="viewOrder">查看订单</el-button>
                            <el-button type="primary" @click="goHome">返回首页</el-button>
                        </div>
                    </template>
                </el-result>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            totalPrice: 0, // 订单总金额
            CartsTableData: [], // 接收购物车传来的商品数据
            activeStep: 0, // 当前步骤
            selectedAddress: null, // 选中的地址

            addressesList: [], // 地址列表

            orderId:0,//订单编号

            vo: {},
            current: 1,
            pageSize: 5,
            total: 0,
            currentList: [5, 10, 20],

            formInline: {
                SearchMerchantAddress: '',
            },
            addressLoading: false, // 新增加载状态

            selectedPayment: null, // 选中的支付方式
            agreeAgreement: false, // 是否同意协议
            paying: false, // 支付中状态
            estimatedDeliveryTime: '', // 预计送达时间
        };
    },
    computed: {
        selectedAddressInfo() {
            return this.addressesList.find(item => item.merchantId === this.selectedAddress) || {};
        },
    },
    methods: {
        async searchMerchant() {
            this.addressLoading = true;
            try {
                const response = await this.$axios.post(`merchant/MerchantsAll/${this.current}/${this.pageSize}`,
                    {
                        ...this.vo,
                        address: this.formInline.SearchMerchantAddress
                    }
                );
                this.addressesList = response.data.list;
                this.total = response.data.total;

                // 如果有默认地址且未被选中，自动选中默认地址
                const defaultAddress = this.addressesList.find(item => item.isDefault);
                if (defaultAddress && !this.selectedAddress) {
                    this.selectedAddress = defaultAddress.merchantId;
                }
            } catch (error) {
                this.$message.error('获取商户列表失败');
                console.error(error);
            } finally {
                this.addressLoading = false;
            }
        },

        // 下一步
        async nextStep(step) {
            if (step === 0) {
                if (!this.selectedAddress) {
                    this.$message.warning('请选择收货地址');
                    return;
                }
                // 获取购物车ID数组
                const cartIds = this.CartsTableData.map(item => item.cartId);
                console.log(777,cartIds)

                let user = JSON.parse(sessionStorage.getItem('user'));

                let order_item = {
                    "userId": user.id,
                    "address": this.selectedAddress, // 地址引用地址id
                    "cartIds": cartIds, // 新增购物车ID数组
                    items: this.CartsTableData.map(item => ({
                        productId: item.product.productId, // 商品 ID
                        sum: item.sum, // 数量
                        price: item.product.salePrice, // 单价（从购物车数据中获取）
                        subtotal: item.product.salePrice * item.sum // 总价
                    }))
                };
                try {
                   this.$axios.post(`order/addOrder`, order_item).then(r =>{
                       console.log(888,r.data)
                       this.orderId = r.data; // 存储订单ID
                       this.$message.success("提交订单成功！！");
                       // this.activeStep++; // 跳转到下一步
                   })
                } catch (error) {
                    this.$message.error("提交失败！");
                }
            } else if (step === 1) {
                if (!this.selectedPayment) {
                    this.$message.warning('请选择支付方式');
                    return;
                }
                // 模拟支付逻辑
                if (Math.random() < 0.1) {
                    this.$message.error('支付失败，请重试');
                    return;
                }
            }
            if (this.activeStep < 2) {
                this.activeStep++;
            }
        },
        // 上一步
        prevStep() {
            if (this.activeStep > 0) {
                this.activeStep--;
            }
        },
        // 页大小
        handleSizeChange(val) {
            this.pageSize = val;
            this.searchMerchant();
        },
        // 页号
        handleCurrentChange(val) {
            this.current = val;
            this.searchMerchant();
        },
        // 点击查询
        onSubmit() {
            this.vo = this.formInline
            this.searchMerchant();
        },
        // 输入地址关键词搜索
        handleSearchClear() {
            this.formInline.SearchMerchantAddress = ''; // 清空
            this.onSubmit();
        },
        // 重置搜索条件
        resetSearch() {
            this.formInline.SearchMerchantAddress = '';
            this.current = 1;
            this.onSubmit();
        },

        // 处理支付
        async handlePayment() {
            if (!this.selectedPayment) {
                this.$message.warning('请选择支付方式');
                return;
            }

            if (!this.agreeAgreement) {
                this.$message.warning('请先阅读并同意支付协议');
                return;
            }

            this.paying = true;
            try {
                // 模拟支付过程
                await new Promise(resolve => setTimeout(resolve, 1500));


                // 计算预计送达时间
                this.calculateDeliveryTime();

                // 跳转到完成步骤
                this.activeStep = 2;

                this.$message.success('支付成功');
            } catch (error) {
                this.$message.error('支付失败: ' + error.message);
            } finally {
                this.paying = false;
            }
        },

        // 计算预计送达时间
        calculateDeliveryTime() {
            const now = new Date();
            const deliveryDate = new Date(now.setDate(now.getDate() + 3));
            const options = {
                year: 'numeric',
                month: 'long',
                day: 'numeric',
                hour: '2-digit',
                minute: '2-digit'
            };
            this.estimatedDeliveryTime = deliveryDate.toLocaleDateString('zh-CN', options);
        },

        // 查看订单
        viewOrder() {
            // this.$router.push(`orderItems/detail/${this.orderId}`);
        },

        // 返回首页
        goHome() {
            this.$router.push('/front_carts');
        },
    },

    created() {
        // // 从路由对象中取出参数
        this.CartsTableData = this.$route.params.selectCartSettlement || [];
        // 计算订单总金额
        this.totalPrice = this.CartsTableData.reduce((total, item) => {
            return total + item.product.salePrice * item.sum;
        }, 0);

        this.searchMerchant();
        console.log(777, this.CartsTableData)
    },
};
</script>

<style scoped>
.el-image2{
    width: 50px;
    height: 50px;
}

.order-checkout {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}

.step-content {
    margin-top: 20px;
}

.address-section,
.payment-section,
.order-info {
    margin-bottom: 20px;
}

.address-list {
    width: 100%;
}

.address-item {
    display: block;
    margin-bottom: 10px;
    padding: 15px;
    border: 1px solid #eee;
    border-radius: 4px;
    transition: all 0.3s;
}

.address-item:hover {
    border-color: #409EFF;
    background-color: #f5f7fa;
}

.address-item.is-checked {
    border-color: #409EFF;
    background-color: #ecf5ff;
}


.no-address {
    text-align: center;
    padding: 20px;
    border: 1px dashed #eee;
    border-radius: 4px;
}

.total-price {
    margin-top: 20px;
    text-align: right;
    font-size: 16px;
}
.address-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;

    h4 {
        margin: 0;
        font-size: 18px;
        color: #333;
    }
}

.address-search {
    width: 300px;

    .el-input-group__append {
        background-color: #409EFF;
        color: white;
        border-color: #409EFF;
        cursor: pointer;

        &:hover {
            opacity: 0.8;
        }
    }
}

.address-container {
    min-height: 200px;
    position: relative;
}

.address-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.address-item {
    margin: 0 !important;
    height: 100%;

    ::v-deep .el-radio__input {
        display: none;
    }

    ::v-deep .el-radio__label {
        padding-left: 0;
        width: 100%;
    }
}

.address-card {
    display: flex;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    transition: all 0.3s;
    height: 100%;
    cursor: pointer;

    &:hover {
        border-color: #409EFF;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    }
}

.address-item.is-checked .address-card {
    border-color: #409EFF;
    background-color: #ecf5ff;
}

.merchant-logo {
    width: 60px;
    height: 60px;
    margin-right: 15px;
    flex-shrink: 0;

    .merchant-image {
        width: 100%;
        height: 100%;
        border-radius: 4px;
        background-color: #f5f7fa;
    }

    .image-error {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f7fa;
        color: #c0c4cc;

        i {
            font-size: 24px;
        }
    }
}

.merchant-info {
    flex: 1;
    min-width: 0;

    .merchant-name {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 8px;
        display: flex;
        align-items: center;

        span {
            margin-right: 10px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    .merchant-address,
    .merchant-contact {
        font-size: 13px;
        color: #606266;
        margin-bottom: 5px;
        display: flex;
        align-items: center;

        i {
            margin-right: 5px;
            color: #909399;
        }

        span {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }
}

.no-address {
    padding: 40px 0;
    text-align: center;
}

.pagination-container {
    margin-top: 20px;
    text-align: center;
}

@media (max-width: 768px) {
    .address-header {
        flex-direction: column;
        align-items: flex-start;

        h4 {
            margin-bottom: 10px;
        }
    }

    .address-search {
        width: 100%;
    }

    .address-list {
        grid-template-columns: 1fr;
    }
}

.step-two {
    max-width: 600px;
    margin: 0 auto;
}

.order-summary-card {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    margin-bottom: 20px;
    overflow: hidden;
}

.order-summary-header {
    padding: 15px 20px;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ebeef5;

    i {
        margin-right: 10px;
        color: #409EFF;
        font-size: 18px;
    }

    span {
        font-weight: 500;
        color: #333;
    }
}

.order-summary-content {
    padding: 15px 20px;
}

.order-info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    color: #606266;

    &.total {
        margin-top: 15px;
        padding-top: 15px;
        border-top: 1px dashed #ebeef5;
        font-size: 16px;

        .total-amount {
            color: #f56c6c;
            font-weight: bold;
            font-size: 18px;
        }
    }
}

.payment-methods {
    width: 100%;
}

.payment-method {
    display: block;
    margin-bottom: 15px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;

    &:hover {
        border-color: #409EFF;
    }

    &.is-checked {
        border-color: #409EFF;
        background-color: #ecf5ff;
    }

    ::v-deep .el-radio__input {
        display: none;
    }

    ::v-deep .el-radio__label {
        padding-left: 0;
    }
}

.payment-content {
    display: flex;
    align-items: center;
}

.payment-icon {
    width: 40px;
    height: 40px;
    margin-right: 15px;
    display: flex;
    align-items: center;
    justify-content: center;

    i {
        font-size: 32px;

        &.icon-alipay {
            color: #00a0e9;
        }

        &.icon-wechat {
            color: #07c160;
        }

        &.el-icon-credit-card {
            color: #409EFF;
        }
    }
}

.payment-info {
    flex: 1;

    .payment-name {
        font-weight: 500;
        margin-bottom: 5px;
    }

    .payment-desc {
        font-size: 12px;
        color: #909399;
    }
}

.payment-agreement {
    margin: 20px 0;
    text-align: center;
}

.action-buttons {
    margin-top: 30px;
    text-align: center;

    .el-button {
        min-width: 120px;
        margin: 0 10px;
    }
}

.step-three {
    max-width: 800px;
    margin: 0 auto;
}

.order-details {
    margin: 20px auto;
    max-width: 500px;
    text-align: left;
}

.detail-item {
    margin-bottom: 10px;

    .detail-label {
        display: inline-block;
        width: 80px;
        color: #909399;
    }

    .detail-value {
        color: #606266;
    }
}

@media (max-width: 768px) {
    .payment-method {
        padding: 10px;
    }

    .payment-icon {
        width: 30px;
        height: 30px;
        margin-right: 10px;

        i {
            font-size: 24px;
        }
    }

    .action-buttons .el-button {
        margin: 5px;
        width: 45%;
    }
}
.payment-methods {
    width: 100%;
}

.payment-method {
    display: block;
    margin-bottom: 15px;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
        border-color: #409EFF;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    }

    &.is-checked {
        border-color: #409EFF;
        background-color: #ecf5ff;
    }

    ::v-deep .el-radio__input {
        display: none;
    }

    ::v-deep .el-radio__label {
        padding-left: 0;
        width: 100%;
    }
}

.payment-content {
    display: flex;
    align-items: center;
    position: relative;
}

.payment-logo {
    width: 40px;
    height: 40px;
    object-fit: contain;
    margin-right: 15px;
}

.payment-info {
    flex: 1;

    .payment-name {
        font-weight: 500;
        margin-bottom: 5px;
        font-size: 16px;
        color: #333;
    }

    .payment-desc {
        font-size: 13px;
        color: #909399;
    }
}

.payment-tag {
    position: absolute;
    right: 10px;
    top: 10px;
}

@media (max-width: 768px) {
    .payment-method {
        padding: 12px;
    }

    .payment-logo {
        width: 32px;
        height: 32px;
        margin-right: 10px;
    }

    .payment-info {
        .payment-name {
            font-size: 14px;
        }

        .payment-desc {
            font-size: 12px;
        }
    }
}
</style>